package com.jqb.webservice.ums.client;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import javax.xml.parsers.DocumentBuilderFactory;

import org.junit.Before;
import org.junit.Test;
import org.w3c.dom.Document;

import ums.webservice.jqb.com.userservice.IUserService;
import ums.webservice.jqb.com.userservice.LicenceInfo;
import ums.webservice.jqb.com.userservice.User;
import ums.webservice.jqb.com.userservice.UserException_Exception;
import ums.webservice.jqb.com.userservice.UserService;

import com.sun.xml.ws.api.message.Header;
import com.sun.xml.ws.api.message.Headers;
import com.sun.xml.ws.developer.WSBindingProvider;

public class UmsClient {

	private String webUrl = "http://localhost:9998/WebService09/UserService?wsdl";
	private String ns = "http://com.jqb.webservice.ums/UserService";
	private String serviceName = "UserService";
	private IUserService userService;
	private UserService us;

	@Before
	public void init() {
		try {
			URL url = new URL(webUrl);
			QName qname = new QName(ns, serviceName);
			us = new UserService(url, qname);
			userService = us.getUserServicePort();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
	}

	@Test
	public void testadd() {
		User user = new User();
		user.setId(1010);
		user.setUsername("dong");
		user.setPassword("dong123");
		// 以头信息的方式加入权限控制
		addLicence();
		try {
			userService.addUser(user);
		} catch (UserException_Exception e) {
			System.out.println(e.getMessage());
		}
	}

	@Test
	public void testGetUsers() {
		List<User> users = userService.getUsers();
		for (User u : users) {
			System.out.println("id:" + u.getId() + " username:" + u.getUsername() + " password:" + u.getPassword());
		}
	}

	private void addLicence() {
		User user = new User();
		user.setId(1000);
		user.setUsername("admin1");
		user.setPassword("admin123");
		LicenceInfo licence = new LicenceInfo();
		licence.setRegisteredUser(user);
		try {
			// 使用JAXB编排对象到xml
			JAXBContext jaxbCtx = JAXBContext.newInstance(LicenceInfo.class);
			QName qname = new QName(ns, "licenceInfo");
			JAXBElement<LicenceInfo> jaxbElement = new JAXBElement<LicenceInfo>(qname, LicenceInfo.class, licence);
			Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
			Marshaller marshaller = jaxbCtx.createMarshaller();
			marshaller.marshal(jaxbElement, doc);
			// 创建头信息
			Header header = Headers.create(doc.getDocumentElement());
			// 绑定头信息(port其实是一个实现了WSBindingProvider和IUserService接口的代理类)
			WSBindingProvider provider = (WSBindingProvider) userService;
			provider.setOutboundHeaders(header);
		} catch (Exception e) {
			System.out.println(e.getMessage());
		}
	}

}
